<script setup lang="ts">
import {toRefs} from "vue";


interface IProps {
    visible: boolean;
    title?: string;
    width?: string | number;
    placement?: "left" | "right" | "top" | "bottom";
    maskClosable?: boolean;
    closeOnEsc?: boolean;
    showFooter?: boolean;
}


interface IEmits {
    (e: "update:show", value: boolean): void;

    (e: "confirm"): void;

    (e: "cancel"): void;
}


const props = withDefaults(defineProps<IProps>(), {
    width: 400,
    placement: "right",
    maskClosable: true,
    closeOnEsc: true,
    showFooter: true
});


const emits = defineEmits<IEmits>();


const {
    visible,
    width,
    placement,
    maskClosable,
    closeOnEsc,
    showFooter
} = toRefs(props);


/**
 * 更新抽屉是否展示
 * @param value
 */
const handleChangeVisible = (value: boolean) => {
    emits("update:show", value);
}


/**
 * 遮罩层事件
 */
const handleMaskClick = () => {
    if (maskClosable.value) {
        handleChangeVisible(false);
        emits("cancel");
    }
}


/**
 * 按键 Esc 事件
 */
const handleEscClick = () => {
    if (closeOnEsc.value) {
        handleChangeVisible(false);
        emits("cancel");
    }
}


/**
 * 取消操作
 */
const handleCancel = () => {
    handleChangeVisible(false);
    emits("cancel");
}


/**
 * 确认操作
 */
const handleConfirm = () => {
    emits("confirm");
}
</script>

<template>
    <div class="common-drawer">
        <n-drawer
            v-model:show="props.visible"
            :width="props.width"
            :placement="props.placement"
            :mask-closable="props.maskClosable"
            :close-on-esc="props.closeOnEsc"
            @update:show="handleChangeVisible"
            @mask-click="handleMaskClick"
            @esc="handleEscClick"
        >
            <n-drawer-content>
                <template #header>
                    <slot name="header">
                        <h4>{{ title }}</h4>
                    </slot>
                </template>

                <div class="drawer-content">
                    <slot name="default"></slot>
                </div>

                <template #footer v-if="props.showFooter">
                    <slot name="footer">
                        <n-space justify="end">
                            <n-button @click="handleCancel">取消</n-button>
                            <n-button type="success" @click="handleConfirm">确认</n-button>
                        </n-space>
                    </slot>
                </template>
            </n-drawer-content>
        </n-drawer>
    </div>
</template>

<style lang="scss">
.common-drawer {
    .drawer-content {
        padding: 12px;
    }
}
</style>